package com.ivanceras.view;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.RichTextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.ivanceras.client.SimulationService;
import com.ivanceras.client.SimulationServiceAsync;
import com.ivanceras.model.Questionnaire;

public class QuestionnaireView {
	public HTML view = new HTML();
	public VerticalPanel edit = new VerticalPanel();;
	
	public Questionnaire questionnaire;

	private TextBox title = new TextBox();
	private RichTextArea desc = new RichTextArea();
	private Button save = new Button("Save");
	
	private final SimulationServiceAsync simulationService = GWT
	.create(SimulationService.class);

	public QuestionnaireView(){
		initLayout();
		initHandlers();
	}
	public void initLayout(){
		edit.add(title);
		edit.add(desc);
		edit.add(save);
	}
	public void initHandlers(){
		title.addKeyUpHandler(new KeyUpHandler(){

			@Override
			public void onKeyUp(KeyUpEvent event) {
				questionnaire.title = title.getText();
			}
			
		});
		desc.addKeyUpHandler(new KeyUpHandler(){

			@Override
			public void onKeyUp(KeyUpEvent event) {
				questionnaire.description = desc.getText();
			}
			
		});
		save.addClickHandler(new ClickHandler(){

			@Override
			public void onClick(ClickEvent event) {
				simulationService.saveQuestionnaire(questionnaire,
						new AsyncCallback<Questionnaire>(){

							@Override
							public void onFailure(Throwable caught) {
								Window.alert("Error saving questionnaire");
							}

							@Override
							public void onSuccess(Questionnaire result) {
								System.out.println("Sucess saving questionnaire");
							}
					
				});
			}
			
		});

	}
	public void setQuestionnaire(Questionnaire qnr){
		this.questionnaire = qnr;
		view.setHTML(qnr.title +" - "+ qnr.description);
		title.setText(qnr.title);
		desc.setHTML(qnr.description);
	}
	
}
